<template>
  <!-- 上传附件 -->
  <el-dialog title="附件管理" width="1000px" :visible.sync="visible" class="uploadDlg_wrap" :destroy-on-close="true">
    <el-card>
      <el-form :inline="true">
        <el-form-item label="附件类型">
          <el-select v-model="appendixType" placeholder="请选择">
            <el-option v-if="ifGetLog" label="全部" value></el-option>
            <el-option label="检验报告" value="检验报告"></el-option>
            <el-option label="电子病历" value="电子病历"></el-option>
            <el-option label="心电电生理" value="心电电生理"></el-option>
            <el-option label="其它" value="其它"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件">
          <!-- :action="'http://192.168.0.91:9200/api/Upload/UnifyUpload?id='+id" -->
          <el-upload
            class="upload-demo"
            ref="upload"
            :action="actionUrl"
            :before-upload="beforeUpload"
            :headers="headers"
            :on-success="handleSuccess"
            multiple
            :limit="fileLimit"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :auto-upload="true"
            :disabled="!appendixType"
          >
            <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
            <el-button
              style="margin-left: 10px;"
              size="small"
              type="primary"
              @click="submitUpload"
              :disabled="!appendixType"
            >点击上传</el-button>
            <div
              slot="tip"
              class="el-upload__tip"
            >提示:目前仅支持上传格式为 jpg,png,pdf,gif,bmp,txt,非标准格式可通过zip上传,文件大小最大为 20 MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="table-wrap">
        <el-table style="width: 100%" max-height="300" :data="logList">
          <el-table-column prop="attachmentName" label="文件名"></el-table-column>
          <el-table-column label="文件类型" width="150">
            <template slot-scope="scope">
              <span>{{scope.row.parentType}}</span>
              <br/>
              <span>({{scope.row.attachmentType}})</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="80"></el-table-column>
          <el-table-column prop="createTime" label="上传时间" width="160"></el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <!-- <span v-html="scope.row.operateType">{{scope.row.operateType}}</span> -->
              <el-button
                v-if="scope.row.operateType"
                type="text"
                size="small"
                @click="handlefile(scope.row, scope.row.operateType)"
              >{{scope.row.operateType=='1'?'预览':'下载'}}</el-button>
              <!-- <el-button @click="handlePreview(scope.$index, scope.row)" type="text" size="small">预览</el-button> -->
              <el-button
                @click="handleDelete(scope.$index, scope.row)"
                style="color:red;"
                type="text"
                size="small"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">退 出</el-button>
    </span>
  </el-dialog>
</template>

<script>

import { getPatAttachmentList, addPatAttachment, deletePatAttachment } from '@/api/api.js'
import { getToken } from '@/utils/auth'
import { sysAppId } from '@/settings.js'
import { getFileRead, getFileDownload, downloadFile, winOpenFile } from '@/api/fileapi'
import { imgReg } from '@/utils/validate'
export default {
  data() {
    return {
      appendixType: '', // 附件类型
      fileLimit: 5,
      fileList: [],
      logList: [],
      visible: false,
      token: '',
      actionUrl: window.g.API_ROOT_JWT + '/api/File/UploadByBuffer',
      headers: {},
      ip: window.g.API_ROOT + '/'
    }
  },
  props: {
    ifGetLog: { // 是否获取列表，会诊申请页面新增状态没有获取列表，编辑状态获取，疫情上报部分获取了
      type: Boolean,
      default: true
    },
    ifEdit: { // 编辑状态
      type: Boolean,
      default: false
    },
    files: { // 已上传的文件
    },
    uploadDialogVisible: {
      type: Boolean,
      default: false
    },
    id: {
    }
  },
  methods: {
    closeDialog() {
      this.$emit('closeDialog')
    },
    submitUpload() {
      if (!this.appendixType) {
        this.$message.error('必须选择一个附件类型')
        return
      }
      this.$refs.upload.submit()
    },
    handleExceed(files, fileList) { // 文件超出个数限制时的
      this.$message.warning(`当前限制选择 ${this.fileLimit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handleSuccess(response, file, fileList) {
      for (let item of response.content.list) {
        let data = {
          parentId: this.id,
          parentType: this.appendixType,
          attachmentName: item.fileName,
          attachmentType: item.contentType,
          fileUrl: item.fileUrl
        }
        addPatAttachment(data).then(res => {
          if (!res) return
          if (this.ifGetLog) {
            this.getList()
          } else {
            // console.log('res.content', res.content)
            let uploadedItem = res.content
            if (!res.content.fileName) {
              if (item.attachmentName == '图片' || imgReg(res.content.attachmentName)) {
                uploadedItem.operateType = '1'
              } else {
                uploadedItem.operateType = '2'
              }
            } else {
              uploadedItem.operateType = ''
            }
            uploadedItem.status = '待提交'
            this.logList.push(uploadedItem)
            this.$emit('getUploadFile', this.logList)
          }
        })
      }
      // console.log('fileList', fileList)
      let n = 0
      if (fileList.length > 0) {
        for (let fitem of fileList) {
          if (fitem.status === 'success') {
            n++
          }
        }
        if (n === fileList.length) {
          this.$refs.upload.clearFiles()
        }
      }
    },
    // handlePreview(file) {
    //   console.log(file)
    // },
    beforeUpload(file) { // 上传文件前对文件类型进行判断
      // console.log('beforeUpload:', file)
      let allFileType = '.jpg,.png,.pdf,.gif,.bmp,.txt,.zip'
      let fileType = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()

      if (!this.appendixType) {
        this.$message.error('必须选择一个附件类型')
        return false
      } else if (!file.size > (20 * 1024 * 1024)) {
        this.$message.error(`文件${file.name}过大，不允许上传超过超过20MB的文件!`)
        return false
      } else if (allFileType.indexOf(fileType) === -1) {
        this.$message.error(`不允许上传的文件类型：${fileType}，请压缩为zip重新上传!`)
        return false
      }
      return true
    },
    getList() {
      let data = {
        parentId: this.id,
        parentType: this.appendixType
      }
      getPatAttachmentList(data).then(res => {
        if (!res) return
        // console.log('getPatAttachmentList', res.content)
        for (let item of res.content.list) {
          if (!item.fileName) {
            if (item.attachmentName == '图片' || imgReg(item.attachmentName)) {
              item.operateType = '1'
            } else {
              item.operateType = '2'
            }
          } else {
            item.operateType = ''
          }
          item.status = '已上传'
        }
        this.logList = res.content.list
        this.$emit('getUploadFile', this.logList)
      })
    },
    deletePatAttachment(i, id) {
      let data = {
        id: id
      }
      deletePatAttachment(data).then(res => {
        if (!res) return
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.logList.splice(i, 1)
      })
    },
    handleDelete(i, row) {
      // if (!this.ifGetLog) {
      //   this.logList.splice(i, 1)
      //   this.$emit('getUploadFile', this.logList)
      //   return
      // }
      // console.log('handleDelete', i, row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deletePatAttachment(i, row.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 附件操作
    handlefile(row, type) {
      if (type == '1') {
        // 预览
        getFileRead(row.fileUrl).then(data => {
          // 新窗口打开
          winOpenFile(row.attachmentName, data)
        })
      } else {
        // 下载
        getFileDownload(row.fileUrl).then(data => {
          downloadFile(row.attachmentName, data)
        })
      }
    },
    setHeaders() {
      let token = this.$store.getters.token
        ? this.$store.getters.token
        : getToken()
          ? getToken()
          : ''
      if (token) {
        this.token = token
        this.headers['Authorization'] = 'Bearer ' + token
        this.headers['sysappid'] = sysAppId
      }
    }
  },
  computed: {
  },
  watch: {
    appendixType() {
      if (this.ifGetLog) {
        this.getList()
      }
    },
    files(val) { // 父删除后子也一起更新删除
      // for (let item of val) {
      //   item.status = '已上传'
      // }
      this.logList = val
    },
    id(val) {
      if (val && this.uploadDialogVisible && this.ifGetLog) {
        this.getList()
      }
    },
    uploadDialogVisible(val) {
      this.visible = val
    },
    visible(val) {
      if (!val) {
        this.closeDialog()
      }
    }
  },
  created() {
    this.setHeaders()
  }
}
</script>

<style lang="scss">
.uploadDlg_wrap {
  .el-upload-list {
    height: 0px;
    overflow: hidden;
  }
}
</style>

